package com.sphd.Restaurant.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ToggleButton;

import com.sphd.Restaurant.R;
import com.sphd.Restaurant.base.BaseActivity;
import com.sphd.Restaurant.model.Model;
import com.sphd.Restaurant.presenter.RegisterP;
import com.sphd.Restaurant.utils.AppManager;
import com.sphd.Restaurant.utils.Constants;
import com.sphd.Restaurant.utils.JsonUtil;
import com.sphd.Restaurant.utils.MyUtils;
import com.sphd.Restaurant.views.ClearEditText;
import com.sphd.Restaurant.views.RegisterView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class RegisterActivity extends BaseActivity implements Handler.Callback, RegisterView, CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_phoneNum)
    ClearEditText etPhoneNum;
    @BindView(R.id.et_password)
    ClearEditText etPassword;
    @BindView(R.id.isShowPassword)
    ToggleButton isShowPassword;
    @BindView(R.id.et_passwordagain)
    ClearEditText etPasswordagain;
    @BindView(R.id.et_verification)
    ClearEditText etVerification;
    @BindView(R.id.tv_obtain)
    Button tvObtain;
    @BindView(R.id.bt_nextto)
    Button btNextto;
    //此APPKEY仅供测试使用，且不定期失效，请到mob.com后台申请正式APPKEY
    private static String APPKEY = "1821134b197de";
    // 填写从短信SDK应用后台注册得到的APPSECRET
    private static String APPSECRET = "6f55db8a086cbad12b69def6c81d71f2";
    @BindView(R.id.layout_obtain)
    LinearLayout layoutObtain;
    private boolean ready;
    private TimeCount time;//倒计时类的实现
    private RegisterP registerP;
    boolean capacity = false;
    private int TYPE = 0;
    Intent intent;
    Bundle bundle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        AppManager.getAppManager().addActivity(this);
        registerP = new RegisterP(this);
        intent = getIntent();
        bundle = intent.getExtras();
        TYPE = bundle.getInt(Constants.TYPE);
        setToolBar(toolbar, TYPE == 0 ? "注册" : TYPE == 1 ? "忘记密码" : "修改密码", true);
        toolbar.setNavigationOnClickListener(view -> AppManager.getAppManager().finishActivity(this));
        if (TYPE == 2) {
            etPhoneNum.setText(getString(Constants.USERPHONE));
           etPhoneNum.setOnFocusChangeListener(null);
            etPhoneNum.setEnabled(false);
            layoutObtain.setVisibility(View.GONE);
        }
        isShowPassword.setOnCheckedChangeListener(this);

    }


    private void initpermissions() {
        RegisterActivityPermissionsDispatcher.onSuccedWithCheck(this);
    }

    @OnClick({R.id.tv_obtain, R.id.bt_nextto})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_obtain:
                checkPhoneNull();
                break;
            case R.id.bt_nextto:
                checkNull();
                break;
        }
    }

    private void checkNull() {
        if (!TextUtils.isEmpty(etPhoneNum.getText().toString().trim())) {
            if (MyUtils.isMobileNO(etPhoneNum.getText().toString().trim())) {
                if (TextUtils.isEmpty(etPassword.getText().toString()) || TextUtils.isEmpty(etPasswordagain.getText().toString())) {
                    new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("密码和确认密码均不能为空")
                            .show();
                } else {
                    if (etPassword.getText().toString().equals(etPasswordagain.getText().toString())) {
                        if (TYPE == 2) {
                            addDate();
                        } else {
                            if (capacity) {
                                addDate();
                            } else {
                                if (!TextUtils.isEmpty(etVerification.getText().toString())) {
                                    //TODO 待验证完毕后记得开启验证
//                                    addDate();
                                SMSSDK.submitVerificationCode("86", etPhoneNum.getText().toString().trim(), etVerification.getText().toString().trim());
                                } else {
                                    new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.ERROR_TYPE)
                                            .setTitleText("验证码不能为空")
                                            .show();
                                }
                            }


                        }

                    } else {
                        new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("两次输入密码不同")
                                .show();
                    }

                }

            } else {
                new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("请输入正确的手机号码")
                        .show();
            }

        } else {
            new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("手机号不能为空")
                    .show();
        }


    }

    private void checkPhoneNull() {
        if (!TextUtils.isEmpty(etPhoneNum.getText().toString().trim())) {
            if (MyUtils.isMobileNO(etPhoneNum.getText().toString().trim())) {
                initpermissions();
            } else {
                new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("请输入正确的手机号码")
                        .show();
            }

        } else {
            new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("手机号不能为空")
                    .show();
        }
    }

    private void initSDK() {
        if (!ready) {

            time = new TimeCount(60000, 1000);//构造CountDownTimer对象
            // 初始化短信SDK
            SMSSDK.initSDK(this, APPKEY, APPSECRET, true);
            final Handler handler = new Handler(this);
            EventHandler eventHandler = new EventHandler() {
                public void afterEvent(int event, int result, Object data) {
                    Message msg = new Message();
                    msg.arg1 = event;
                    msg.arg2 = result;
                    msg.obj = data;
                    handler.sendMessage(msg);
                }
            };
            // 注册回调监听接口
            SMSSDK.registerEventHandler(eventHandler);
            ready = true;
        }
        SMSSDK.getVerificationCode("86", etPhoneNum.getText().toString().trim());
        toast("已发送");
        time.start();//开始倒计时

    }

    @NeedsPermission({Manifest.permission.READ_CONTACTS,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECEIVE_SMS,
            Manifest.permission.READ_EXTERNAL_STORAGE})
    void onSucced() {
        Log.e("OK", "OK");
        initSDK();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        RegisterActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.READ_CONTACTS,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECEIVE_SMS,
            Manifest.permission.READ_EXTERNAL_STORAGE})
    void onCause(final PermissionRequest request) {
        giveMsg(request);
        Log.e("onCause", "onCause");
    }

    @OnPermissionDenied({Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onBreak() {
        showHelp();
        Log.e("onBreak", "onBreak");
    }

    @OnNeverAskAgain({Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onNever() {
        showHelp();
        Log.e("onNever", "onNever");
    }
    private void giveMsg(PermissionRequest request) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("提示");
        builder.setMessage("应用运行需获取电话、短信等权限。请许可授权");
        // 拒绝, 退出应用
        builder.setNegativeButton("算了吧", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
//                request.cancel();
                AppManager.getAppManager().finishActivity(RegisterActivity.this);
            }
        });

        builder.setPositiveButton("去授权", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                request.proceed();
            }
        });

        builder.setCancelable(false);
        builder.show();
    }

    private void showHelp() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.help);
        builder.setMessage(R.string.string_help_text);

        // 拒绝, 退出应用
        builder.setNegativeButton("算了吧", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                AppManager.getAppManager().finishActivity(RegisterActivity.this);
            }
        });

        builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });

        builder.setCancelable(false);

        builder.show();
    }





    @Override
    public boolean handleMessage(Message msg) {
        int event = msg.arg1;
        int result = msg.arg2;
        Object data = msg.obj;
        if (result == SMSSDK.RESULT_COMPLETE) {
            if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                addDate();
            } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                boolean smart = (Boolean) data;
                if (smart) {
                    //通过智能验证
                    toast("您已通过智能验证，无需再次输入验证码。");
                    layoutObtain.setVisibility(View.GONE);
                    capacity = true;
                } else {
                    //依然走短信验证
                    capacity = false;
                    layoutObtain.setVisibility(View.VISIBLE);
                }
            }
        } else if (result == SMSSDK.RESULT_ERROR) {
            ((Throwable) data).printStackTrace();
            Log.e("data", data.toString());
            toast(JsonUtil.getJsonObject(((Throwable) data).getMessage()).getString("detail"));
        }
        return false;

    }

    private void addDate() {
        MyUtils myUtils = new MyUtils();
        if (TYPE == 0) {
            registerP.addData(Model.HTTPURL + Model.REGISTER + "username=" + etPhoneNum.getText().toString().trim()
                    + "&password=" + myUtils.getkeyBeanofStr(etPasswordagain.getText().toString().trim()));
        } else {
            registerP.addData(Model.HTTPURL + Model.FORGET + "username=" + etPhoneNum.getText().toString().trim()
                    + "&password=" + myUtils.getkeyBeanofStr(etPasswordagain.getText().toString().trim()));
        }
    }

    @Override
    protected void onDestroy() {
        if (ready) {
            // 销毁回调监听接口
            SMSSDK.unregisterAllEventHandler();
        }
        super.onDestroy();
    }

    @Override
    public void sendRes(int res) {
        if (TYPE == 0) {
            new SweetAlertDialog(context, res == 0 ? SweetAlertDialog.SUCCESS_TYPE : res == 2 ? SweetAlertDialog.ERROR_TYPE : SweetAlertDialog.SUCCESS_TYPE)
                    .setTitleText(res == 0 ? "注册失败" : res == 2 ? "该手机号已注册" : "注册成功").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    sweetAlertDialog.dismiss();
                    //注册成功后跳转到添加资料的界面
                    if (res == 1) {
                        AppManager.getAppManager().finishActivity(LoginActivity.class);
                        Intent intent = new Intent();
                        intent.putExtra(Constants.TAG, context.getClass().getName());
                        intent.putExtra(Constants.USERPHONE, etPhoneNum.getText().toString().trim());
                        intent.putExtra(Constants.PWD, etPasswordagain.getText().toString().trim());
                        intent.setClass(context, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishActivity(RegisterActivity.class);
                    }
                }
            }).show();
        } else {
            new SweetAlertDialog(context, res == 0 ? SweetAlertDialog.ERROR_TYPE : SweetAlertDialog.SUCCESS_TYPE)
                    .setTitleText(res == 0 ? "修改失败" : "修改成功").
                    setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            //注册成功后跳转到添加资料的界面
                            if (res == 1) {
                                if (TYPE == 2) {
                                    AppManager.getAppManager().finishActivity(MainActivity.class);
                                } else {
                                    AppManager.getAppManager().finishActivity(LoginActivity.class);
                                }
                                Intent intent = new Intent();
                                intent.putExtra(Constants.TAG, context.getClass().getName());
                                intent.putExtra(Constants.USERPHONE, etPhoneNum.getText().toString().trim());
                                intent.putExtra(Constants.PWD, etPasswordagain.getText().toString().trim());
                                intent.setClass(context, LoginActivity.class);
                                startActivity(intent);
                                AppManager.getAppManager().finishActivity(RegisterActivity.class);
                            }

                        }
                    }).show();


        }
    }

    @Override
    public void showdialog() {
            showDialog();
    }

    @Override
    public void dissmissdialog() {
           dissMissDialog();
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        switch (compoundButton.getId()) {
            case R.id.isShowPassword:
                if (isChecked) {
                    //隐藏
                    etPassword.setInputType(0x90);
                    etPasswordagain.setInputType(0x90);

                } else {
                    //明文显示
                    etPassword.setInputType(0x81);
                    etPasswordagain.setInputType(0x81);
                }
                break;
        }
    }


    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tvObtain.setBackgroundResource(R.color.main_bottom_down);
            tvObtain.setClickable(false);
            tvObtain.setText(millisUntilFinished / 1000 + "秒后获取");
        }

        @Override
        public void onFinish() {
            //计时完毕时触发
            tvObtain.setText("重新验证");
            tvObtain.setBackgroundResource(R.color.mycolor);
            tvObtain.setClickable(true);
        }
    }
}
